<?php

require_once '../params.inc';
require_once '../session.inc';
require_once '../utils.inc';
require_once '../shop.inc';
require_once '../data.inc';
require_once 'sf.inc';

if ($par->exist('del')) 
{
	$keyFields = new DecodedFieldValues($par->get('keys'));
	$productId = $keyFields->getValueOf('cf_products.id');
	
	Product::del($productId);

	$fmgr = new Files('products');
	$fInfo = new Fields('products');
	$fInfo->open();
	
	while ($fInfo->fetch()) 
	{
		if ($fInfo->type() == FIELD_TYPE_FILE) 
		{
			$a = array('cf_products.id'=>$productId);
			$fmgr->del($fInfo->name(), $a, '../../');
		}
	}
	
	header("Location: " . $par->get('target'));
	exit;
}

$action = $par->get('do');

if ('groups' == $action)
{
	$productId = $par->get('productId');
	$posInGroup = array_fill_keys($par->exist('groups') ? $par->get('groups') : array(), null);

	$qExist = createQuery("
		SELECT sort_order
		FROM cf_products_in_groups 
		WHERE product_id=$productId AND group_id=:groupId
	");
	
	foreach ($posInGroup as $groupId => $pos) 
	{
		$qExist->setParam('groupId', $groupId);
		$qExist->execute();
		if ($qExist->fetch())
		{
			$posInGroup[$groupId] = $qExist->at(0);
		}
		$qExist->close();
	}
	
	execQuery("
		DELETE FROM cf_products_in_groups
		WHERE product_id=$productId
	");
	
	
	$qInsert = createQuery("
		INSERT INTO cf_products_in_groups
			(product_id, group_id, sort_order)
		VALUES ($productId, :groupId, :pos)
	");

	foreach ($posInGroup as $groupId => $pos) 
	{
		$qInsert->setParam('groupId', $groupId);
		$qInsert->setParam('pos', $pos);
		$qInsert->execute();
		$qInsert->close();
	}
		
	
	header("Location: edit_product_attrs.php?productId=$productId");
	exit;
}
elseif ('attributes' == $action) 
{
	$productId = $par->get('productId');
	
	$attributes = new ProductAttributes($productId, true);
	foreach ($attributes as $attr) 
	{
		$parName = 'attribute_' . $attr->id();
		if ($par->exist($parName)) 
		{
			$attr->setValue($par->get($parName));
		}
	}
	
	$product = new Product($productId);
	$product->setAttributes($attributes);
	
	session::open();
	$target = session::get('cf_orig_target');
	
	header("Location: $target");
	exit;
}
?>